package cn.chess.service.impl;

import cn.chess.domain.User;
import cn.chess.mapper.UserMapper;
import cn.chess.service.UserService;
import cn.chess.util.WXConst;
import cn.chess.vo.WxUserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;

import static cn.chess.util.WXConst.WxGetOpenIdUrl;

/**
 * @author zgc
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-03-27 10:32:16
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    WXConst wxApp;
    @Resource
    RestTemplate restTemplate;


    @Override
    public int update(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", user.getOpenid());
        return userMapper.update(user, queryWrapper);
    }

    @Override
    public WxUserVo getWxUser(String code) {
        String url = WxGetOpenIdUrl +
                "appid=" + WXConst.appId +
                "&secret=" + WXConst.appSecret +
                "&js_code=" + code +
                "&grant_type=" + WXConst.grant_type;

        WxUserVo wxUserVo = restTemplate.getForObject(url, WxUserVo.class);
        String openid = wxUserVo.getOpenid();
//判读新用户
        initUser(openid);

        return wxUserVo;
    }

    @Override
    public void initUser(String openid) {

//        判断用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setBalance(new BigDecimal("0.0"));
            userMapper.insert(user);
        }

    }

    @Override
    public User getUserByOpenid(String openid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);

        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserById(Integer userid) {

        return userMapper.selectById(userid);
    }
}




